package com.ibm.moa.outmail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ibm.moa.outmail.adapter.ExpandableListViewAdapter;
import com.ibm.moa.outmail.adapter.ExpandableListViewAdapter.DeleteMailListener;
import com.ibm.moa.outmail.module.MailInfo;
import com.ibm.moa.outmail.net.HttpManage;
import com.ibm.moa.outmail.net.HttpRequestListener;
import com.ibm.moa.outmail.utils.ParserRequest;
import com.ibm.moa.outmail.utils.UIEventListener;
import com.ibm.moa.outmail.utils.Utils;

public class SearchActivity extends BaseActivity implements OnClickListener,HttpRequestListener, DeleteMailListener{
	private ImageView ivBack;
	private ExpandableListViewAdapter mailListAdapter;
	private ExpandableListView expListView;
	private LinearLayout footer_view;
	private ProgressBar footer_probar;
	private TextView footer_text;
	private List<String> timeTitles;
	private ArrayList<MailInfo> tempMailInfoList;
	private Map<Integer, List<MailInfo>> mailInfoMap;
	
	private EditText content;
	private ImageView searchBT;
	private Dialog dialog;
	private int pageid = 1;
	private int pagesize = 10;
	
	@SuppressWarnings("unchecked")
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			if(dialog != null){
				dialog.dismiss();
				dialog = null;
			}
			switch (msg.what) {
			case UIEventListener.EVENT_GET_DATA_FEFRESH_SUCCESS:
				HashMap<String, String> map = (HashMap<String, String>) msg.obj;
				if(map != null ){
					if("1".equals(map.get("req_code"))){
						int total = 0;
						String mail_cnt = map.get("mail_cnt");
						try{
							total = Integer.valueOf(mail_cnt);
						}catch (Exception e) {
							total = -1;
						}
						mailInfoMap.clear();

						//将临时集合中的数据拷贝到Map集合中
						Utils.copyMailList2MailMap(tempMailInfoList, mailInfoMap, timeTitles);
						
						tempMailInfoList.clear();
						if(mailListAdapter == null){
							mailListAdapter = new ExpandableListViewAdapter(SearchActivity.this, timeTitles, mailInfoMap, SearchActivity.this);
							expListView.setAdapter(mailListAdapter);
							
							for(int i = 0; i < expListView.getCount(); i++){
								expListView.expandGroup(i);
							}
						}else{
							mailListAdapter.notifyDataSetChanged();
						}
						
						if(total <= 0){
							expListView.setVisibility(View.GONE);
							TextView nodataTV = (TextView) findViewById(R.id.no_data_tv);
							nodataTV.setVisibility(View.VISIBLE);
						}else{
							expListView.setVisibility(View.VISIBLE);
							TextView nodataTV = (TextView) findViewById(R.id.no_data_tv);
							nodataTV.setVisibility(View.GONE);
						}
						
						if(Utils.getMapSize(mailInfoMap) == total){
							if(expListView.getFooterViewsCount()>0){
								expListView.removeFooterView(footer_view);
					    	}
						}else{
							if(expListView.getFooterViewsCount()<1){
								expListView.addFooterView(footer_view);
					    	}
						}
						
					}else{
						Toast.makeText(SearchActivity.this, (String) map.get("req_mess")==null ? "返回信息错误": (map.get("req_mess")+""), Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case UIEventListener.EVENT_GET_DATA_MORE_SUCCESS:
				HashMap<String, String> mapMore = (HashMap<String, String>) msg.obj;
				if(mapMore != null ){
					if("1".equals(mapMore.get("req_code"))){
						int totalMore = 0;
						try{
							totalMore = Integer.valueOf(mapMore.get("mail_cnt"));
						}catch (Exception e) {
							totalMore = -1;
						}
						
						//将临时集合中的数据拷贝到Map集合中
						Utils.copyMailList2MailMap(tempMailInfoList, mailInfoMap, timeTitles);
						
						tempMailInfoList.clear();
						if(mailListAdapter == null){
							mailListAdapter = new ExpandableListViewAdapter(SearchActivity.this, timeTitles, mailInfoMap, SearchActivity.this);
							expListView.setAdapter(mailListAdapter);
							
							for(int i = 0; i < expListView.getCount(); i++){
								expListView.expandGroup(i);
							}
						}else{
							mailListAdapter.notifyDataSetChanged();
						}
						
						if(totalMore <= 0){
							expListView.setVisibility(View.GONE);
							TextView nodataTV = (TextView) findViewById(R.id.no_data_tv);
							nodataTV.setVisibility(View.VISIBLE);
						}else{
							expListView.setVisibility(View.VISIBLE);
							TextView nodataTV = (TextView) findViewById(R.id.no_data_tv);
							nodataTV.setVisibility(View.GONE);
						}
						
						if(Utils.getMapSize(mailInfoMap) == totalMore){
							if(expListView.getFooterViewsCount()>0){
								expListView.removeFooterView(footer_view);
					    	}
						}else{
							if(expListView.getFooterViewsCount()<1){
								expListView.addFooterView(footer_view);
					    	}
						}
					}else{
						Toast.makeText(SearchActivity.this, (String) mapMore.get("req_mess")==null ? "返回信息错误": (mapMore.get("req_mess")+""), Toast.LENGTH_SHORT).show();
					}
				}
				footer_probar.setVisibility(View.GONE);
				footer_text.setText("更多");
				break;
			case UIEventListener.EVENT_GET_DATA_FEFRESH_FAILURE:
				Toast.makeText(SearchActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			case UIEventListener.EVENT_GET_DATA_MORE_FAILURE:
				footer_probar.setVisibility(View.GONE);
				footer_text.setText("更多");
				Toast.makeText(SearchActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		
		initView();
	}
	
	
	private void initView() {
		ivBack = (ImageView) findViewById(R.id.home_back_iv);
		ivBack.setOnClickListener(this);
		content = (EditText) findViewById(R.id.search_content_et);
		searchBT = (ImageView) findViewById(R.id.search_button_iv);
		searchBT.setOnClickListener(this);
		
        expListView = (ExpandableListView) findViewById(R.id.home_mail_list);
        footer_view = (LinearLayout) View.inflate(this, R.layout.listview_footer_view, null);
		footer_probar = (ProgressBar) footer_view.findViewById(R.id.listview_footer_view_progressbar);
		footer_text = (TextView) footer_view.findViewById(R.id.listview_footer_view_text);
		footer_view.setOnClickListener(this);
		expListView.addFooterView(footer_view);
		
        timeTitles = new ArrayList<String>();      
    	mailInfoMap = new TreeMap<Integer, List<MailInfo>>();
    	tempMailInfoList = new ArrayList<MailInfo>();
	}

	@Override
	public void onClick(View v) {
		if(v == ivBack){
			finish();
		} else {
			String keyWord = content.getText().toString().trim();
			
			if(TextUtils.isEmpty(keyWord)){
				Toast.makeText(this, "请输入要搜索的关键字", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if(v == searchBT){
				pageid = 1;
				HashMap<String , String> map = new HashMap<String, String>();
				map.put("invoke", "searchMail");
			    map.put("userCode", MailApplication.userCode);
			    map.put("password", MailApplication.passWord);
			    map.put("searchCond", keyWord);
			    map.put("pageNo", pageid+"");
			    map.put("pageSize", pagesize+"");
			    map.put("readFlag", "0");
			    new HttpManage(this, this, map, 1);
			    dialog = Utils.createProgressDialog(this, Utils.getLoadingMessage(SearchActivity.this, "加载中..."));
				dialog.show();
			}else if(v == footer_view){
				++pageid;
				HashMap<String , String> map = new HashMap<String, String>();
				map.put("invoke", "searchMail");
			    map.put("userCode", MailApplication.userCode);
			    map.put("password", MailApplication.passWord);
			    map.put("searchCond", keyWord);
			    map.put("pageNo", pageid+"");
			    map.put("pageSize", pagesize+"");
			    map.put("readFlag", "0");
			    new HttpManage(this, this, map, 2);
			    footer_probar.setVisibility(View.VISIBLE);
				footer_text.setText("获取数据...");
			}
		}
	}


	@Override
	public void action(int actionCode, String resultStr, int httpFlag) {
		switch (actionCode) {
		case HttpRequestListener.EVENT_GET_DATA_SUCCESS:
			Log.i("lgs", resultStr);
			switch (httpFlag) {
			case 1:
				try{
					HashMap<String, String> map = ParserRequest.ParsReceiveMailList(resultStr, tempMailInfoList);
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FEFRESH_SUCCESS, map);
					moreMeg.sendToTarget();
				}catch (Exception e) {
					e.printStackTrace();
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FEFRESH_FAILURE, "返回信息错误");
					moreMeg.sendToTarget();
				}
				break;
			case 2:
				try{
					HashMap<String, String> map = ParserRequest.ParsReceiveMailList(resultStr, tempMailInfoList);
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_MORE_SUCCESS,map);
					moreMeg.sendToTarget();
				}catch (Exception e) {
					e.printStackTrace();
					Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_MORE_FAILURE, "返回信息错误");
					moreMeg.sendToTarget();
				}
				break;
			}
			
			break;
		case HttpRequestListener.EVENT_GET_DATA_FAIL:
			switch (httpFlag) {
			case 1:
				Message moreMeg = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_FEFRESH_FAILURE, "获取网络信息失败");
				moreMeg.sendToTarget();
				break;
			case 2:
				Message moreMeg1 = handler.obtainMessage(UIEventListener.EVENT_GET_DATA_MORE_FAILURE, "获取网络信息失败");
				moreMeg1.sendToTarget();
				break;
			}
			break;
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case 10:
				if(data != null && data.getStringExtra("mailId") != null){
					String mailId = data.getStringExtra("mailId");
					for(int i = 0; i< mailInfoMap.size(); i++){
						List<MailInfo> list = mailInfoMap.get(i);
						
						for(int j = 0; null != list && j < list.size(); j++){
							if(mailId.equals(list.get(j).mailId)){
								mailInfoMap.get(i).remove(j);
								break;
							}
						}
					}
					if(mailListAdapter  != null){
						mailListAdapter.notifyDataSetChanged();
					}
				}
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}


	@Override
	public void deleteMail(MailInfo mailInfo) {
		
	}

	@Override
	public void onItemClicked(View parent, MailInfo mailInfo) {
		Intent intent = new Intent(SearchActivity.this, MailInfoActivity.class);
		intent.putExtra("mailId", mailInfo.mailId);
		startActivityForResult(intent, 10);
		if(mailInfo.readFlag){
			mailInfo.readFlag = true;
			if(mailListAdapter!= null){
				mailListAdapter.notifyDataSetChanged();
			}
		}
	}

}
